import numpy as np


def pso_optimize(obj_func, n_particles, max_iter, velocity_limit, search_range, c1, c2, w):
    """
    粒子群优化算法
    :param obj_func: 目标函数
    :param n_particles: 粒子数量
    :param max_iter: 最大迭代次数
    :param velocity_limit: 速度限制
    :param search_range: 搜索范围
    :param c1: 加速常数 1
    :param c2: 加速常数 2
    :param w: 惯性权重
    :return: 全局最优位置和全局最优分数
    """
    positions = np.random.randint(search_range[0], search_range[1], (n_particles, 2))
    velocities = np.random.uniform(velocity_limit[0], velocity_limit[1], (n_particles, 2))
    pbest = positions.copy()
    pbest_scores = np.array([obj_func(pos[0], pos[1]) for pos in positions])
    gbest = positions[np.argmin(pbest_scores)]
    gbest_score = pbest_scores.min()


    for _ in range(max_iter):
        for i in range(n_particles):
            r1, r2 = np.random.rand(2)
            velocities[i] = (
                w * velocities[i]
                + c1 * r1 * (pbest[i] - positions[i])
                + c2 * r2 * (gbest - positions[i])
            )
            positions[i] = np.clip(positions[i] + velocities[i], *search_range)
            score = obj_func(int(positions[i][0]), int(positions[i][1]))
            if score < pbest_scores[i]:
                pbest[i], pbest_scores[i] = positions[i], score
                if score < gbest_score:
                    gbest, gbest_score = pbest[i], score
    return gbest, gbest_score